import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';

@Injectable()
export class EncryptionService {
  private readonly saltRounds = 10;

  /**
   * 加密密码
   * @param plainPassword 明文密码
   * @returns 加密后的密码
   */
  async hashPassword(plainPassword: string): Promise<string> {
    return bcrypt.hash(plainPassword, this.saltRounds);
  }

  /**
   * 比较密码
   * @param plainPassword 明文密码
   * @param hashedPassword 加密后的密码
   * @returns 密码是否匹配
   */
  async comparePassword(plainPassword: string, hashedPassword: string): Promise<boolean> {
    // 未加密的密码处理（仅用于开发阶段，生产环境应始终使用加密密码）
    if (!hashedPassword.startsWith('$2')) {
      return plainPassword === hashedPassword;
    }

    return bcrypt.compare(plainPassword, hashedPassword);
  }

  /**
   * 生成随机密码
   * @param length 密码长度
   * @returns 随机密码
   */
  generateRandomPassword(length = 8): string {
    const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+';
    let password = '';

    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * charset.length);
      password += charset[randomIndex];
    }

    return password;
  }
} 